package com.markerhub.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.InspectionImage;
import com.markerhub.service.InspectionImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Arrays;
import java.util.UUID;

/**
 * 巡检图片Controller
 */
@Api(tags = "巡检图片管理")
@RestController
@RequestMapping("/api/inspection-image")
public class InspectionImageController extends BaseController {

    @Autowired
    private InspectionImageService inspectionImageService;

    @Value("${file.upload-dir:./uploads}")
    private String uploadDir;

    /**
     * 获取巡检图片列表 - 分页
     */
    @ApiOperation(value = "获取巡检图片列表", notes = "获取所有巡检图片信息，支持分页查询")
    @PreAuthorize("hasAuthority('inspection:image:list')")
    @GetMapping("/list")
    public Result list(InspectionImage image) {
        Page<InspectionImage> page = inspectionImageService.page(getPage(), new QueryWrapper<InspectionImage>()
                .eq(image.getRecord_id() != null, "record_id", image.getRecord_id()));
        return Result.succ(200, "获取巡检图片列表成功", page);
    }

    /**
     * 查询巡检图片 - 分页
     */
    @ApiOperation(value = "查询巡检图片", notes = "根据条件查询巡检图片信息，支持分页")
    @PreAuthorize("hasAuthority('inspection:image:query')")
    @GetMapping("/query")
    public Result query(InspectionImage image) {
        return list(image);
    }

    /**
     * 根据ID获取巡检图片信息
     */
    @ApiOperation(value = "获取巡检图片详情", notes = "根据图片ID获取指定巡检图片的详细信息")
    @PreAuthorize("hasAuthority('inspection:image:list')")
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable Long id) {
        InspectionImage image = inspectionImageService.getById(id);
        return Result.succ(200, "获取巡检图片信息成功", image);
    }

    /**
     * 创建巡检图片记录
     */
    @ApiOperation(value = "新增巡检图片记录", notes = "新增巡检图片记录")
    @PreAuthorize("hasAuthority('inspection:image:add')")
    @PostMapping("/add")
    public Result add(@Validated @RequestBody InspectionImage image) {
        image.setCreated(new Date());
        boolean saved = inspectionImageService.save(image);
        return saved ? Result.succ(200, "创建巡检图片记录成功", image) : Result.fail("创建巡检图片记录失败");
    }

    /**
     * 删除单个巡检图片
     */
    @ApiOperation(value = "删除巡检图片", notes = "删除指定ID的巡检图片")
    @PreAuthorize("hasAuthority('inspection:image:delete')")
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Long id) {
        InspectionImage image = inspectionImageService.getById(id);
        if (image != null && image.getImage_url() != null) {
            // 删除物理文件
            File file = new File(uploadDir + File.separator + image.getImage_url());
            if (file.exists()) {
                file.delete();
            }
        }
        boolean deleted = inspectionImageService.removeById(id);
        return deleted ? Result.succ(200, "删除巡检图片成功", null) : Result.fail("删除巡检图片失败");
    }

    /**
     * 批量删除巡检图片
     */
    @ApiOperation(value = "批量删除巡检图片", notes = "批量删除多个巡检图片")
    @PreAuthorize("hasAuthority('inspection:image:delete')")
    @DeleteMapping("/delete")
    public Result delete(@RequestBody Long[] ids) {
        // 批量删除物理文件
        for (Long id : ids) {
            InspectionImage image = inspectionImageService.getById(id);
            if (image != null && image.getImage_url() != null) {
                File file = new File(uploadDir + File.separator + image.getImage_url());
                if (file.exists()) {
                    file.delete();
                }
            }
        }
        boolean deleted = inspectionImageService.removeByIds(Arrays.asList(ids));
        return deleted ? Result.succ(200, "批量删除巡检图片成功", null) : Result.fail("批量删除巡检图片失败");
    }

    /**
     * 上传图片
     */
    @ApiOperation(value = "上传图片", notes = "上传巡检图片文件")
    @PreAuthorize("hasAuthority('inspection:image:upload')")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, 
                        @RequestParam(value = "recordId", required = false) Long recordId,
                        @RequestParam(value = "deviceId", required = false) Long deviceId) {
        try {
            // 验证文件大小和类型
            if (file.isEmpty()) {
                return Result.fail("上传文件不能为空");
            }
            
            // 确保上传目录存在
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = StringUtils.getFilenameExtension(originalFilename);
            String filename = UUID.randomUUID().toString() + "." + fileExtension;
            
            // 保存文件
            Path path = Paths.get(uploadDir, filename);
            Files.write(path, file.getBytes());
            
            // 创建图片记录
            InspectionImage image = new InspectionImage();
            image.setImage_url(filename);
            image.setDescription(originalFilename);
            image.setRecord_id(recordId);
            image.setCreated(new Date());
            
            inspectionImageService.save(image);
            
            return Result.succ(200, "图片上传成功", image);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("图片上传失败：" + e.getMessage());
        }
    }

    /**
     * 下载图片
     */
    @ApiOperation(value = "下载图片", notes = "下载巡检图片文件")
    @PreAuthorize("hasAuthority('inspection:image:download')")
    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> download(@PathVariable Long id) {
        try {
            InspectionImage image = inspectionImageService.getById(id);
            if (image == null || image.getImage_url() == null) {
                throw new RuntimeException("图片不存在");
            }
            
            Path path = Paths.get(uploadDir, image.getImage_url());
            Resource resource = new FileSystemResource(path);
            
            if (!resource.exists()) {
                throw new RuntimeException("图片文件不存在");
            }
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + image.getDescription());
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            throw new RuntimeException("下载图片失败：" + e.getMessage());
        }
    }
}